﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Package_EditPackage : AdminBasePage
{
    public tblPackage Package { get; set; }
    public tblPayment Payment { get; set; }

    BLLPackageManagement bllPackageManagement = new BLLPackageManagement();
    string barcode;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        barcode = Request.QueryString["barcode"];
        //        barcode = "13082012000080";

        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(barcode))
            {
                Package = bllPackageManagement.GetPackage(barcode);

                if (Package != null)
                {
                    Payment = bllPackageManagement.GetPayment(Package.ID);
                    if (Payment != null)
                    {
                        bind();
                    }
                    else
                    {
                        Response.Redirect("~/Admin/Package/ListPackage.aspx");
                    }
                }
                else
                {
                    Response.Redirect("~/Admin/Package/ListPackage.aspx");
                }
            }
            else
            {
                Response.Redirect("~/Admin/Package/ListPackage.aspx");
            }
        }

    }

    private void bind()
    {
        bindStatus();
        bindCountry();
        bindParcelType();
        bindData();
        bindTransit(barcode);
        bindBranch();
    }

    private void bindStatus()
    {
        ddlStatus.DataSource = bllPackageManagement.ListPackageStatus();
        ddlStatus.DataTextField = "StatusName";
        ddlStatus.DataValueField = "ID";
        ddlStatus.DataBind();
    }

    private void bindCountry()
    {

        ddlCountry.DataSource = bllPackageManagement.getCountries();
        ddlCountry.DataTextField = "Country";
        ddlCountry.DataValueField = "ID";
        ddlCountry.DataBind();

        ddlReCountry.DataSource = ddlCountry.DataSource;
        ddlReCountry.DataTextField = "Country";
        ddlReCountry.DataValueField = "ID";
        ddlReCountry.DataBind();
    }

    /// <summary>
    /// bind parcel type to ddlParcelType
    /// </summary>
    private void bindParcelType()
    {
        BLLShipment bll = new BLLShipment();
        ddlParcelType.DataSource = bll.getAllParcelType();
        ddlParcelType.DataTextField = "ParcelType";
        ddlParcelType.DataValueField = "ID";
        ddlParcelType.DataBind();
    }

    /// <summary>
    /// Bind all the package info to according fields
    /// </summary>
    private void bindData()
    {
        if (Package == null)
            return;
        tblCustomer receiver = Package.tblCustomerReceiver;
        tblCustomer sender = Package.tblCustomerSender;

        hiddID.Value = Package.Barcode.ToString();

        txtName.Text = sender.Name;
        txtEmail.Text = sender.Email;
        txtNRIC.Text = sender.NRIC;
        txtContact.Text = sender.Contact;
        txtBlock.Text = sender.Block;
        txtStreet.Text = sender.Street;
        txtCity.Text = sender.City;
        txtProvince.Text = sender.Province;
        ddlCountry.SelectedValue = sender.Country.Value.ToString();

        txtReName.Text = receiver.Name;
        txtReContact.Text = receiver.Contact;
        txtReBlock.Text = receiver.Block;
        txtReStreet.Text = receiver.Street;
        txtReCity.Text = receiver.City;
        txtReProvince.Text = receiver.Province;
        ddlReCountry.SelectedValue = sender.Country.Value.ToString();

        ddlParcelType.SelectedValue = Package.ParcelType.Value.ToString();
        txtWeight.Text = string.Format("{0:.00}", Package.Weight);
        ddlFragile.SelectedValue = Package.Fragile.ToString();
        ddlStatus.SelectedValue = Package.Status.ToString();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        Package = bllPackageManagement.GetPackage(hiddID.Value);
        Payment = bllPackageManagement.GetPayment(Package.ID);

        if (Package != null)
        {

            tblCustomer senderCustomer = Package.tblCustomerSender;
            senderCustomer.Name = txtName.Text;
            senderCustomer.NRIC = txtNRIC.Text;
            senderCustomer.Block = txtBlock.Text;
            senderCustomer.Street = txtStreet.Text;
            senderCustomer.City = txtCity.Text;
            senderCustomer.Province = txtProvince.Text;
            senderCustomer.Country = Convert.ToInt16(ddlCountry.SelectedValue);
            senderCustomer.Contact = txtContact.Text;
            senderCustomer.Email = txtEmail.Text;

            tblCustomer receiverCustomer = Package.tblCustomerReceiver;
            receiverCustomer.Name = txtReName.Text;
            receiverCustomer.Block = txtReBlock.Text;
            receiverCustomer.Street = txtReStreet.Text;
            receiverCustomer.City = txtReCity.Text;
            receiverCustomer.Province = txtReProvince.Text;
            receiverCustomer.Country = Convert.ToInt16(ddlReCountry.SelectedValue);
            receiverCustomer.Contact = txtReContact.Text;

            Package.ParcelType = Convert.ToInt16(ddlParcelType.SelectedValue);
            Package.Fragile = Convert.ToBoolean(ddlFragile.SelectedValue);
            Package.Weight = Convert.ToDecimal(txtWeight.Text);
            Package.Status = Convert.ToInt16(ddlStatus.SelectedValue);

            decimal countryFee = Package.tblCustomerReceiver.tblCountry.PriceRate.Value;
            decimal additonalFee = Package.tblParcelType.AdditionalFee.Value;
            Payment.Price = Package.Weight.Value * countryFee + additonalFee;
            Payment.IsDone = false;
            Payment.CreatedDate = DateTime.Now;

        }
        bllPackageManagement.UpdatePackage();
        bllPackageManagement.UpdatePayment();
        Response.Redirect("~/Admin/Package/ViewPackage.aspx?barcode=" + hiddID.Value);
    }



    #region Route Management
    protected int first_transitid = 0;

    private void bindTransit(string barcode)
    {
        tblPackage package = bllPackageManagement.GetPackage(barcode);

        if (package != null)
        {
            int packageid = package.ID;

            List<vTransitRecord> lst = bllPackageManagement.ListTransitByPackageID(packageid);
            if (lst.Count > 0)
            {
                first_transitid = lst[0].TransitID;
                gvTransit.DataSource = lst;
                gvTransit.DataBind();



                //(gvTransit.Rows[0].FindControl("btnDelete") as LinkButton).Visible = false;

            }
        }
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        //dlvTransit.EditItemIndex = 0;
        //bindTransit(barcode);
    }


    protected void gvTransit_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddTransit")
        {
            int transitid = Convert.ToInt16(e.CommandArgument);
            tblTransit transit = bllPackageManagement.GetTransit(transitid);
            if (transit != null)
            {
                hidCurrentTransit.Value = transit.ID.ToString();
                lblCurrentBranchName.Text = transit.tblBranch.Name;
                panelNew.Visible = true;
            }
            bindBranch();
            bindTransit(barcode);
        }
        else if (e.CommandName == "DelTransit")
        {
            int transitid = Convert.ToInt16(e.CommandArgument);

            bllPackageManagement.DelTransit(transitid);
            bindBranch();
            bindTransit(barcode);
        }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int _currentTransitID = Convert.ToInt16(hidCurrentTransit.Value);
        tblTransit transit = bllPackageManagement.GetTransit(_currentTransitID);
        if (transit != null)
        {
            tblTransit newTransit = new tblTransit()
            {
                PackageID = transit.PackageID,
                BranchID = Convert.ToInt16(ddlBranch.SelectedValue),
                Status = 0,
            };

            if (transit.NextTransitID != 0)
            {
                newTransit.NextTransitID = transit.NextTransitID;
            }

            bllPackageManagement.NewTransit(newTransit);
            transit.NextTransitID = newTransit.ID;
            bllPackageManagement.UpdateTransit();

            panelNew.Visible = false;
        }
        bindBranch();
        //ddlBranch.Items.Remove(ddlBranch.SelectedItem);
        bindTransit(barcode);
    }

    protected void gvTransit_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvTransit.EditIndex = e.NewEditIndex;
        bindTransit(barcode);
    }
    protected void gvTransit_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        DropDownList ddl = gvTransit.Rows[e.RowIndex].FindControl("ddlBranch") as DropDownList;
        HiddenField hid = gvTransit.Rows[e.RowIndex].FindControl("hidID") as HiddenField;

        if (ddl != null && hid != null)
        {
            int transitid = Convert.ToInt16(hid.Value);
            int branchid = Convert.ToInt16(ddl.SelectedValue);

            tblTransit transit = bllPackageManagement.GetTransit(transitid);
            if (transit != null)
            {
                transit.BranchID = branchid;
            }
            bllPackageManagement.UpdateTransit();
        }
        gvTransit.EditIndex = -1;
        bindTransit(barcode);
    }
    protected void gvTransit_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvTransit.EditIndex = -1;
        bindTransit(barcode);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        panelNew.Visible = false;
        lblCurrentBranchName.Text = "";
        bindTransit(barcode);
    }
    protected void gvTransit_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

    private void bindBranch()
    {
        ddlBranch.DataSource = bllPackageManagement.ListBranches(barcode);

        ddlBranch.DataTextField = "Name";
        ddlBranch.DataValueField = "ID";
        ddlBranch.DataBind();
        ddlBranch_SelectedIndexChanged(ddlBranch,null);
    }

    private List<tblBranch> _branches;
    public List<tblBranch> lstBranch
    {
        get
        {
            if (_branches == null)
            {
                _branches = bllPackageManagement.ListBranches();
            }
            return _branches;
        }
    }

    #endregion
    protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
    {
        int id = Convert.ToInt16(ddlBranch.SelectedValue);
        tblBranch branch = bllPackageManagement.GetBranch(id);
        if (branch != null)
        {
            lblBranchAddress.Text = branch.Address;
            lblBranchCountry.Text = branch.tblCountry.Country;
        }
    }
}